package com.example.exam1.service;

import com.example.exam1.dao.BookDao;
import com.example.exam1.entity.Book;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author wushuang
 * recorrected by Deepwind
 */
public class BookService {
    BookDao bookDao = new BookDao();

    /**
     * 从csv文件导入图书数据
     *
     * @return 状态码
     */
    public int fromCSV() {
        File file = new File(this.getClass().getResource("/").toString().substring(6) + "book.csv");
        int status = 1;

        try {
            // 初始化
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line = "";

            // 循环遍历文件行
            while (((line = bufferedReader.readLine()) != null)) {
                Book book = new Book();
                String[] str = line.split(",");
                String name = str[0];
                String author = str[1];
                String number = str[2];

                // 跳过第一行
                if ("name".equals(name)) {
                    continue;
                }

                book.setName(name);
                book.setAuthor(author);
                book.setNumber(number);

                // 检查是否存在图书重复
                if (bookDao.isBookExisted(book)) {
                    status = 0;
                } else {
                    bookDao.addBook(book);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return status;
    }

    /**
     * 删除图书
     *
     * @param book Book
     * @return 状态码
     */
    public int delBook(Book book) {
        return bookDao.delBook(book);
    }

    /**
     * 搜索图书
     *
     * @param book Book
     * @return 状态码
     */
    public Book searchBook(Book book) {
        return bookDao.searchBook(book);
    }

    /**
     * 更新图书
     *
     * @param book Book
     * @return 状态码
     */
    public int updateBook(Book book) {
        return bookDao.updateBook(book);
    }
}
